import { defineComponent, onMounted, h } from "vue";

import { loadScript } from "@/utils";
import adConfig from "./adConfigs";

const currAdConfig = adConfig.default || {};

// Keep track of defined ad slots.
const scripts_map: any = {
  gpt: "https://securepubads.g.doubleclick.net/tag/js/gpt.js",
  adsense: `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7826482262281669`,
};

export const GPTScript = defineComponent({
  name: "GPTScript",
  setup() {
    const script_types = currAdConfig.script_types || ["gpt", "adsense"];

    if (script_types && script_types.length) {
      for (let i = 0; i < script_types.length; i++) {
        const type = script_types[i];
        const script = scripts_map[type];
        if (script) {
          loadScript(script, () => {
            console.log(`${type} script loaded：` + script);
          });
        }
      }
    }
    return () => h("div", { style: { display: "none" } });
  },
});

export const DefineAdsenseSlot = defineComponent({
  name: "DefineAdsenseSlot",
  props: {
    adUnit: {
      type: Number,
      required: false,
      default: "",
    },
    wrapStyle: {
      type: Object,
      required: false,
      default: () => ({}),
    },
    extProps: {
      type: Object,
      required: false,
      default: () => ({})
    }
  },
  setup(props) {
    onMounted(() => {
      // @ts-ignore
      (window.adsbygoogle = window.adsbygoogle || []).push({});
    });
    return () =>
      h("ins", {
        class: "adsbygoogle",
        style: props.wrapStyle,
        "data-ad-client": "ca-pub-7826482262281669",
        "data-ad-slot": props.adUnit,
        ...props.extProps
      });
  },
});
